<template>
  <div v-show="!isMain && !isView" class="add-equip-detail">
    <px-scrollbar class="add-equip-content">
      <px-button style="margin: 16px 0 -4px" type="primary" icon="ArrowLeft" @click="backMainPage">返回</px-button>
      <px-form ref="formRef" :inline="true" :model="formValue" :rules="rules" label-position="right" label-width="150px">
        <EditDropDown dropdownTitle="基本信息">
          <template v-slot:content>
            <px-row>
              <px-col :span="8">
                <px-form-item label="点检计划编号" prop="planNo">
                  <px-input v-model="formValue.planNo" disabled placeholder="自动生成" maxlength="50" clearable />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="点检计划名称" prop="planName">
                  <px-input v-model="formValue.planName" placeholder="请输入点检计划名称" maxlength="50" clearable />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <EquipClassSelect :isRequired="true" :className="formValue.className" @changeClassName="changeClassName" />
              </px-col>
              <px-col :span="8">
                <EquipSystemTree
                  :isRequired="true"
                  :className="formValue.className"
                  :systemCode="formValue.systemCode"
                  propValue="systemCode"
                  @changeAllSystemCodes="changeAllSystemCodes"
                  @changeSystemCodes="changeSystemCodes"
                  @clearSystem="clearSystem"
                />
              </px-col>
              <px-col :span="8">
                <px-form-item label="设备编号" prop="eqpId">
                  <px-input
                    v-model="formValue.eqpId"
                    placeholder="请点击选择"
                    maxlength="50"
                    disabled
                    style="width: calc(100% - 108px); margin-right: 8px"
                  />
                  <px-button type="primary" plain style="width: 100px" @click="dialogVisible = true">选择设备</px-button>
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="设备名称" prop="eqpName">
                  <px-input v-model="formValue.eqpName" disabled placeholder="根据设备编号获取" maxlength="50" />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="设备位置" prop="positionName">
                  <px-input v-model="formValue.positionName" disabled placeholder="根据设备编号获取" maxlength="50" />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="任务分配" prop="groupCode">
                  <px-select v-model="formValue.groupCode" placeholder="请选择" clearable :disabled="!formValue.className" @focus="handleGroupFocus">
                    <px-option v-for="item in groupList" :key="item.code" :label="item.name" :value="item.code" />
                  </px-select>
                </px-form-item>
              </px-col>
            </px-row>
          </template>
        </EditDropDown>
        <EditDropDown dropdownTitle="异常信息">
          <template v-slot:content>
            <px-row style="width: 100%">
              <px-col :span="8">
                <px-form-item label="异常来源" prop="unnormalSource">
                  <px-select v-model="formValue.unnormalSource" placeholder="请选择异常来源">
                    <px-option v-for="item in shareData.faultSourceList" :key="item.id" :label="item.name" :value="item.value" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="异常单号" prop="relatedOrderNum">
                  <px-input
                    v-model="formValue.relatedOrderNum"
                    maxlength="50"
                    placeholder="请输入异常单号"
                    :disabled="!formValue.unnormalSource"
                    clearable
                  />
                </px-form-item>
              </px-col>
            </px-row>
            <px-row style="width: 100%">
              <px-col :span="24">
                <px-form-item label="异常描述" prop="unnormalDesc">
                  <px-input
                    v-model="formValue.unnormalDesc"
                    type="textarea"
                    placeholder="请输入异常描述"
                    :autosize="{ minRows: 2, maxRows: 4 }"
                    maxlength="1000"
                    clearable
                  />
                </px-form-item>
              </px-col>
              <px-col :span="24">
                <px-form-item label="异常图片" prop="imageIds">
                  <PhotoUpload
                    v-if="!isMain && !isView"
                    :photoType="photoType"
                    :photoData="{ moduleName: moduleName }"
                    :photoList="formValue.imageIds"
                    style="margin-bottom: 18px"
                    @changePhotoList="changePhotoList"
                    @savePhotoStatus="savePhotoStatus"
                  />
                </px-form-item>
              </px-col>
              <px-col :span="24">
                <px-form-item label="点检建议" prop="checkAdvice">
                  <px-input
                    v-model="formValue.checkAdvice"
                    type="textarea"
                    placeholder="请输入点检建议"
                    :autosize="{ minRows: 2, maxRows: 4 }"
                    maxlength="1000"
                  />
                </px-form-item>
              </px-col>
            </px-row>
          </template>
        </EditDropDown>
        <EditDropDown dropdownTitle="执行周期">
          <template v-slot:content>
            <ExecutionCycle :form-value="formValue" :show-create-task="false" :referSource="'exception'" @change="handelExecutionCycleChange" />
          </template>
        </EditDropDown>
        <px-form ref="contentFormRef" :model="contentList">
          <div v-for="(item, index) in contentList" :key="index">
            <EditDropDown :dropdownTitle="item.isTableEdit === 'edit' ? '新增项目内容' : item.checkContentName">
              <template v-slot:btn>
                <px-button v-if="item.isTableEdit === 'view'" link type="primary" @click="editTable(index)">编辑</px-button>
                <px-popconfirm
                  width="220"
                  confirm-button-text="删除"
                  cancel-button-text="取消"
                  :icon="InfoFilled"
                  icon-color="#f59e0b"
                  confirm-button-type="warning"
                  title="是否要删除当前内容"
                  @confirm="deleteTable(index, item.id)"
                >
                  <template #reference>
                    <px-button v-if="item.isTableEdit === 'view'" link type="danger">删除</px-button>
                  </template>
                </px-popconfirm>
                <px-button v-if="item.isTableEdit === 'edit'" link type="primary" @click="saveTable(contentFormRef, index)">保存</px-button>
                <px-popconfirm
                  width="220"
                  confirm-button-text="确认"
                  cancel-button-text="取消"
                  :icon="InfoFilled"
                  icon-color="#909399"
                  confirm-button-type="primary"
                  title="内容没保存，确认取消?"
                  @confirm="cancelTable(index)"
                >
                  <template #reference>
                    <px-button v-if="item.isTableEdit === 'edit'" link type="primary">取消</px-button>
                  </template>
                </px-popconfirm>
              </template>
              <template v-slot:content>
                <px-form-item
                  v-if="item.isTableEdit === 'edit'"
                  label="巡检项内容"
                  :prop="index + '.checkContentName'"
                  :rules="[{ required: true, message: '巡检项内容不能为空', trigger: 'blur' }]"
                >
                  <px-input v-model="item.checkContentName" placeholder="请输入巡检项内容" maxlength="50" clearable />
                </px-form-item>
                <px-table
                  :data="item.pointCheckContentItemList"
                  class="equip-table"
                  :class="item.isTableEdit === 'view' ? 'inspect-table-view' : 'inspect-table-edit'"
                  size="small"
                  border
                >
                  <px-table-column v-if="item.isTableEdit === 'view'" fixed="left" type="index" label="序号" width="60" />
                  <px-table-column fixed="left" prop="checkItem" label="巡检项" min-width="160" show-overflow-tooltip :render-header="renderHeader">
                    <template #default="scope">
                      <template v-if="item.isTableEdit === 'view'">{{ scope.row.checkItem }}</template>
                      <template v-else>
                        <px-form-item
                          label-width="0px"
                          label=""
                          :prop="index + '.pointCheckContentItemList.' + scope.$index + '.checkItem'"
                          :rules="[{ required: true, message: '巡检项不能为空', trigger: 'blur' }]"
                        >
                          <px-input v-model="scope.row.checkItem" placeholder="请输入巡检项" maxlength="50" clearable />
                        </px-form-item>
                      </template>
                    </template>
                  </px-table-column>
                  <px-table-column prop="checkContent" label="巡检内容" min-width="100" show-overflow-tooltip :render-header="renderHeader">
                    <template #default="scope">
                      <template v-if="item.isTableEdit === 'view'">{{ scope.row.checkContent }}</template>
                      <template v-else>
                        <px-form-item
                          label-width="0px"
                          label=""
                          :prop="index + '.pointCheckContentItemList.' + scope.$index + '.checkContent'"
                          :rules="[{ required: true, message: '巡检内容不能为空', trigger: 'blur' }]"
                        >
                          <px-input v-model="scope.row.checkContent" placeholder="请输入巡检内容" maxlength="50" clearable />
                        </px-form-item>
                      </template>
                    </template>
                  </px-table-column>
                  <px-table-column prop="checkContentRangeValue" label="内容范围" min-width="160" show-overflow-tooltip :render-header="renderHeader">
                    <template #default="scope">
                      <template v-if="scope.row.checkContentRange !== 4">
                        <template v-if="item.isTableEdit === 'view' && scope.row.checkContentRange === 1">文本</template>
                        <template v-if="item.isTableEdit === 'view' && scope.row.checkContentRange === 2">数字</template>
                        <template v-if="item.isTableEdit === 'view' && scope.row.checkContentRange === 3 && scope.row.checkContentRangeValue">
                          判断：True={{ scope.row.checkContentRangeValue.split(",")[0] }}; False={{ scope.row.checkContentRangeValue.split(",")[1] }}
                        </template>
                        <template v-if="item.isTableEdit === 'edit' && scope.row.checkContentRange === 1">
                          <px-select v-model="scope.row.checkContentRange" placeholder="请选择内容范围" style="width: 100%">
                            <px-option v-for="item in checkContentRangeList" :key="item.value" :label="item.label" :value="item.value" />
                          </px-select>
                        </template>
                        <template v-if="item.isTableEdit === 'edit' && scope.row.checkContentRange === 2">
                          <px-select v-model="scope.row.checkContentRange" placeholder="请选择内容范围" style="width: 100%">
                            <px-option v-for="item in checkContentRangeList" :key="item.value" :label="item.label" :value="item.value" />
                          </px-select>
                        </template>
                        <div v-if="item.isTableEdit === 'edit' && scope.row.checkContentRange === 3" style="display: flex; align-items: center">
                          <px-select v-model="scope.row.checkContentRange" placeholder="请选择内容范围" style="width: 20%">
                            <px-option v-for="item in checkContentRangeList" :key="item.value" :label="item.label" :value="item.value" />
                          </px-select>
                          &nbsp;&nbsp;True=
                          <px-form-item
                            style="width: 25%"
                            label-width="0px"
                            label=""
                            :prop="index + '.pointCheckContentItemList.' + scope.$index + '.checkContentRangeValue1'"
                            :rules="[
                              {
                                required: item.isTableEdit === 'edit' && scope.row.checkContentRange === 3,
                                message: 'True值不能为空',
                                trigger: 'blur'
                              }
                            ]"
                          >
                            <px-input v-model="scope.row.checkContentRangeValue1" placeholder="请输入内容" maxlength="50" clearable />
                          </px-form-item>
                          &nbsp;&nbsp;False=
                          <px-form-item
                            style="width: 25%"
                            label-width="0px"
                            label=""
                            :prop="index + '.pointCheckContentItemList.' + scope.$index + '.checkContentRangeValue2'"
                            :rules="[
                              {
                                required: item.isTableEdit === 'edit' && scope.row.checkContentRange === 3,
                                message: 'False值不能为空',
                                trigger: 'blur'
                              }
                            ]"
                          >
                            <px-input v-model="scope.row.checkContentRangeValue2" placeholder="请输入内容" maxlength="50" clearable />
                          </px-form-item>
                          &nbsp;&nbsp;
                          <px-tooltip content="无法输入带逗号（','）的字符" placement="top">
                            <px-icon><QuestionFilled /></px-icon>
                          </px-tooltip>
                        </div>
                      </template>
                      <template v-else>
                        <template v-if="item.isTableEdit === 'view'"> 选择：{{ scope.row.checkContentRangeValue }} </template>
                        <template v-else>
                          <px-form-item
                            label-width="0px"
                            label=""
                            :prop="index + '.pointCheckContentItemList.' + scope.$index + '.checkContentRangeValue'"
                            :rules="[
                              {
                                required: item.isTableEdit === 'edit' && scope.row.checkContentRange === 4,
                                validator: checkRangeCode,
                                trigger: 'blur'
                              }
                            ]"
                          >
                            <px-input
                              v-model="scope.row.checkContentRangeValue"
                              placeholder="请输入选项，并以英文逗号（','）分割"
                              maxlength="50"
                              clearable
                              style="width: 90%"
                            >
                              <template #prepend>
                                <px-select v-model="scope.row.checkContentRange" placeholder="请选择内容范围" style="width: 120px">
                                  <px-option v-for="item in checkContentRangeList" :key="item.value" :label="item.label" :value="item.value" />
                                </px-select>
                              </template>
                            </px-input>
                            &nbsp;&nbsp;
                            <px-tooltip content="以英文逗号（','）分割" placement="top">
                              <px-icon><QuestionFilled /></px-icon>
                            </px-tooltip>
                          </px-form-item>
                        </template>
                      </template>
                    </template>
                  </px-table-column>
                  <px-table-column v-if="item.isTableEdit === 'edit'" fixed="right" label="操作" width="60" align="center">
                    <template #default="scope">
                      <px-button
                        link
                        type="danger"
                        icon="Delete"
                        :disabled="scope.$index === 0 && contentList[index].pointCheckContentItemList.length === 1"
                        @click="deleteItem(index, scope.$index)"
                      />
                    </template>
                  </px-table-column>
                </px-table>
                <div
                  v-if="item.isTableEdit === 'edit'"
                  style="
                    width: 100%;
                    height: 32px;
                    margin-bottom: 18px;
                    line-height: 32px;
                    color: #3b82f6;
                    text-align: center;
                    cursor: pointer;
                    border: 1px dashed #3b82f6;
                    border-radius: 4px;
                  "
                  @click="addTableItem(index)"
                >
                  新增巡检项
                </div>
              </template>
            </EditDropDown>
          </div>
        </px-form>
        <div v-if="showAddContent" style="margin-top: 16px">
          <px-button type="primary" @click="addTable">新增项目内容</px-button>
        </div>
      </px-form>
    </px-scrollbar>
    <div class="info-form-btns">
      <px-button @click="backMainPage">取消</px-button>
      <px-button v-if="formValue.planStatus !== 2" type="primary" plain :disabled="photoStatusFlag" @click="handleSubmit(formRef, 'draft')"
        >保存草稿</px-button
      >
      <px-button type="primary" :disabled="photoStatusFlag || saveContentDisabled" @click="handleSubmit(formRef)">发布点检计划</px-button>
    </div>
    <!-- 选择设备弹窗 -->
    <EquipIdSelectDialog
      :visible="dialogVisible"
      :className="formValue.className"
      :systemCodes="systemCodes"
      @closeEquipDialog="closeEquipDialog"
      @changeEqpId="changeEqpId"
    />
  </div>
</template>
<script setup lang="ts">
import {
  addExceptionDraft,
  addExceptionList,
  detailExceptionList,
  editExceptionDraft,
  editExceptionList,
  getModuleName,
  getPlanCode
} from "@/api/equip/exception";
import { getOpsGroupList } from "@/api/equip/maintain";
import PhotoUpload from "@/components/Upload/PhotoUpload.vue";
import EditDropDown from "@/views/all/equip/components/EditDropDown.vue";
import EquipClassSelect from "@/views/all/equip/components/EquipClassSelect.vue";
import EquipIdSelectDialog from "@/views/all/equip/components/EquipIdSelectDialog.vue";
import EquipSystemTree from "@/views/all/equip/components/EquipSystemTree.vue";
import { ExecutionCycle } from "@/views/erc/inspect/components/index";
import { InfoFilled } from "@px-ui/icons-vue";
import { PxMessage, PxMessageBox } from "px-ui";
import { computed, h, reactive, ref, toRefs, watch } from "vue";

// 调用父级-返回主页、查询列表方法
const emits = defineEmits(["backMainPage", "queryTable"]);
// 父级传过来的值
const props = defineProps(["isMain", "isView", "drawerType", "shareData", "planNo"]);
// 显示隐藏
const isMain = computed(() => props.isMain);
const isView = computed(() => props.isView);

// 页面本身的值
const formRef = ref();
const contentFormRef = ref();

const state = reactive<any>({
  formValue: {
    className: "",
    systemCode: "",
    eqpId: "",
    eqpName: ""
  },
  contentList: [],
  photoType: "add",
  moduleName: "",
  photoStatusFlag: false,
  dialogVisible: false,
  groupList: [], // 运维组列表
  checkContentRangeList: [
    { label: "文本", value: 1 },
    { label: "数字", value: 2 },
    { label: "判断", value: 3 },
    { label: "选择", value: 4 }
  ], // 巡检内容范围列表
  checkRuleTempData: {}, // 临时保存巡检内容表格数据，为了取消使用
  isAdd: false,
  systemCodes: []
});

const {
  formValue,
  contentList,
  photoType,
  moduleName,
  photoStatusFlag,
  dialogVisible,
  groupList,
  checkContentRangeList,
  checkRuleTempData,
  isAdd,
  systemCodes
} = toRefs(state);

// 表单校验规则
const rules = computed(() => ({
  planNo: [{ required: true, message: "点检计划编号不能为空", trigger: "blur" }],
  planName: [{ required: true, message: "点检计划名称不能为空", trigger: "blur" }],
  eqpId: [{ required: true, message: "设备编号不能为空", trigger: "blur" }],
  groupCode: [{ required: true, message: "任务分配的组不能为空", trigger: "blur" }],
  unnormalDesc: [{ required: true, message: "异常描述不能为空", trigger: "change" }],
  execType: [
    {
      required: true,
      message: "请选择执行方式",
      trigger: "change"
    }
  ],
  execStartDate: [
    {
      required: true,
      message: "请选择开始日期",
      trigger: "change"
    }
  ],
  execEndDate: [
    {
      required: true,
      message: "请选择结束日期",
      trigger: "change"
    }
  ],
  execDuration: [
    {
      required: true,
      message: "请选择执行时长",
      trigger: "blur"
    }
  ],
  taskCreateTime: [
    {
      required: true,
      message: "请选择任务生成并提醒时间",
      trigger: "change"
    }
  ]
}));

// 巡检内容禁用条件
const saveContentDisabled = computed(() => {
  if (contentList.value.length === 0) return true;
  if (
    contentList.value.every(item => {
      return item.isTableEdit === "view";
    })
  ) {
    return false;
  }
  return true;
});

const handelExecutionCycleChange = val => {
  Object.assign(formValue.value, val);
};

// 判断类-内容范围-选择
const checkRangeCode = (rule: any, value: any, callback: any) => {
  if (value == "") {
    callback(new Error("选项不能为空"));
  } else if (!/,/.test(value)) {
    callback(new Error("请输入选项，并以英文逗号（','）分割"));
  } else {
    callback();
  }
};

// 获取后端自动生成的工单号
const getToolCode = async () => {
  const data = await getPlanCode();
  formValue.value.planNo = data;
};

// 获取运维组列表数据
const handleGroupFocus = async () => {
  groupList.value = await getOpsGroupList({ className: formValue.value.className });
};

// 监视isMain和isView值
watch(props, async () => {
  if (!props.isMain && !props.isView) {
    getModuleNameValue();
    formRef.value?.resetFields();
    if (props.drawerType === "add") {
      formValue.value.extendDurationUnit = "HOUR";
      await getToolCode();
      photoType.value = "add";
    } else if (props.drawerType === "edit") {
      await getDetail();
      photoType.value = "edit";
    } else if (props.drawerType === "copy") {
      await getDetail();
      await getToolCode();
      photoType.value = "add";
    }
  } else {
    formValue.value = {
      className: "",
      systemCode: "",
      eqpId: "",
      eqpName: "",
      contentList: []
    };
  }
});
// 获取getModuleName
const getModuleNameValue = async () => {
  const data = await getModuleName();
  moduleName.value = data;
};

const showAddContent = computed(() => {
  if (
    contentList.value.length === 0 ||
    contentList.value.every(item => {
      return item.isTableEdit === "view";
    })
  ) {
    return true;
  }
  return false;
});

// 新增判断类表格
const addTable = () => {
  isAdd.value = true;
  contentList.value.push({
    checkItemContent: "",
    isTableEdit: "edit",
    pointCheckContentItemList: [
      {
        checkItem: "",
        checkContent: "",
        checkContentRange: 1,
        checkContentRangeValue: ""
      }
    ]
  });
  checkRuleTempData.value[contentList.value.length - 1] = JSON.parse(JSON.stringify(contentList.value[contentList.value.length - 1]));
};
// 保存判断类表格
const saveTable = async (formEl, index) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      contentList.value[index].isTableEdit = "view";
      if (contentList.value[index].pointCheckContentItemList && contentList.value[index].pointCheckContentItemList.length > 0) {
        contentList.value[index].pointCheckContentItemList.forEach(item => {
          if (item.checkContentRange === 3) {
            item.checkContentRangeValue = item.checkContentRangeValue1 + "," + item.checkContentRangeValue2;
          }
        });
      }
    }
  });
};

const deleteTable = index => {
  contentList.value.splice(index, 1);
};
// 取消判断类表格
const cancelTable = index => {
  if (isAdd.value) {
    contentList.value.splice(index, 1);
    checkRuleTempData.value[index] = {};
    isAdd.value = false;
  } else {
    contentList.value[index] = checkRuleTempData.value[index];
    checkRuleTempData.value[index] = JSON.parse(JSON.stringify(contentList.value[index]));
  }
};
// 编辑判断类表格
const editTable = index => {
  contentList.value[index].isTableEdit = "edit";
  checkRuleTempData.value[index] = contentList.value[index];
  if (contentList.value[index].pointCheckContentItemList && contentList.value[index].pointCheckContentItemList.length > 0) {
    contentList.value[index].pointCheckContentItemList.forEach(item => {
      if (item.checkContentRange === 3) {
        item.checkContentRangeValue1 = item.checkContentRangeValue.split(",")[0];
        item.checkContentRangeValue2 = item.checkContentRangeValue.split(",")[1];
      }
    });
  }
  checkRuleTempData.value[index] = JSON.parse(JSON.stringify(contentList.value[index]));
  checkRuleTempData.value[index].isTableEdit = "view";
};
// 新增抄表类、判断类某一行
const addTableItem = index => {
  // 判断类
  contentList.value[index].pointCheckContentItemList.push({
    checkItem: "",
    checkContent: "",
    checkContentRange: 1,
    checkContentRangeValue: ""
  });
};
// 删除抄表类、判断类某一行
const deleteItem = async (index, $index) => {
  contentList.value[index].pointCheckContentItemList.splice($index, 1);
};
// 表格头部渲染-添加必填*
const renderHeader = (column: any) => {
  // 在最外层插入一个div标签
  return h(
    "div",
    {
      style: ""
    },
    [
      h(
        "label",
        {
          style: "",
          class: "must"
        },
        column.column.label
      )
    ]
  );
};

// 获取详情接口
const getDetail = async () => {
  const data = await detailExceptionList(props.planNo);
  formValue.value = JSON.parse(JSON.stringify(data));
  if (props.drawerType === "copy") {
    delete data.id;
    formValue.value.planName = "";
    formValue.value.execStartDate = "";
    formValue.value.execEndDate = "";
    formValue.value.planStatus = 1;
    formValue.value.planStatus = "";
    delete formValue.value.id;
  }
  const { images, execType, contentList: list, systemCode } = data;
  formValue.value.execType = String(execType);
  // 巡检规则内容
  contentList.value = list || [];
  if (contentList.value.length > 0) {
    contentList.value.forEach(item => {
      item.isTableEdit = "view";
    });
  }
  if (images && images?.length > 0) {
    images?.forEach(item => {
      item.url = item.fileUrl;
    });
    formValue.value.imageIds = data.images;
  } else {
    formValue.value.imageIds = [];
  }
  handleGroupFocus();
};
// 返回主页面
const backMainPage = () => {
  PxMessageBox.confirm(`确认退出工单吗？退出后内容将不会保存，请谨慎操作`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      formRef.value.resetFields();
      contentList.value = [];
      emits("backMainPage");
    })
    .catch(() => {});
};
// 新的图片列表
const changePhotoList = val => {
  formValue.value.imageIds = val;
};
// 图片是否上传完，是否可以保存
const savePhotoStatus = val => {
  photoStatusFlag.value = val;
};
// 提交
const handleSubmit = async (formEl: any, type?: any) => {
  if (!formEl) return;
  const params = formValue.value;
  const imgList = [];
  const { imageIds } = formValue.value;
  if (imageIds && imageIds?.length > 0) {
    imageIds?.forEach(item => {
      if (item?.id) {
        imgList.push(item.id);
      } else if (item?.response.data.id) {
        imgList.push(item.response.data.id);
      }
    });
  }
  params.contentList = contentList.value;
  // 保存草稿不需要对数据进行校验
  if (type === "draft") {
    console.log("保存草稿");
    if (props.drawerType === "add" || props.drawerType === "copy") {
      await addExceptionDraft({ ...params, imageIds: imgList });
      PxMessage.success("保存草稿成功");
      formRef.value.resetFields();
      contentList.value = [];
      emits("backMainPage");
      emits("queryTable");
    } else if (props.drawerType === "edit") {
      await editExceptionDraft({ id: props.planNo, ...params, imageIds: imgList });
      PxMessage.success("编辑草稿成功");
      formRef.value.resetFields();
      contentList.value = [];
      emits("backMainPage");
      emits("queryTable");
    }
  } else {
    await formEl.validate(async valid => {
      if (valid) {
        if (props.drawerType === "add" || props.drawerType === "copy") {
          await addExceptionList({ ...params, imageIds: imgList });
          PxMessage.success("创建成功");
          formRef.value.resetFields();
          contentList.value = [];
          emits("backMainPage");
          emits("queryTable");
        } else if (props.drawerType === "edit") {
          await editExceptionList({ id: props.planNo, ...params, imageIds: imgList });
          PxMessage.success("编辑成功");
          formRef.value.resetFields();
          contentList.value = [];
          emits("backMainPage");
          emits("queryTable");
        }
      }
    });
  }
};
// 关闭子级设备dialog弹窗
const closeEquipDialog = () => {
  dialogVisible.value = false;
};

// 外部封装好的组件
// 科室组件调用父组件
const changeClassName = (val, isOnlyClass) => {
  formValue.value.className = val;
  systemCodes.value = [];
  if (!isOnlyClass) {
    formRef.value?.resetFields(["systemCode", "eqpId", "eqpName"]);
    formValue.value.positionName = "";
    formValue.value.groupCode = "";
  }
};
// 系统组件调用父组件
const changeAllSystemCodes = (val, val2, val3, val4) => {
  formValue.value.className = val2;
  formValue.value.systemCode = val3;
  systemCodes.value = val4;
  formRef.value?.resetFields(["eqpId", "eqpName"]);
  formValue.value.positionName = "";
};
// 系统组件调用父组件
const changeSystemCodes = (val, val2) => {
  formValue.value.systemCode = val;
  systemCodes.value = val2;
  formRef.value?.resetFields(["eqpId", "eqpName"]);
  formValue.value.positionName = "";
};
// 系统组件值改变触发
const clearSystem = val => {
  systemCodes.value = [];
  formRef.value?.resetFields(["systemCode", "eqpId", "eqpName"]);
  formValue.value.positionName = "";
};
// 改变设备编号
const changeEqpId = equipDetail => {
  formValue.value.className = equipDetail?.className || "";
  formValue.value.systemCode = equipDetail?.systemCode || "";
  systemCodes.value = [];
  formValue.value.eqpId = equipDetail?.eqpId || "";
  formValue.value.eqpName = equipDetail?.eqpName || "";
  formValue.value.positionName = equipDetail?.positionNameAll || "";
};
</script>
<style lang="scss" scoped>
@import url("@/views/all/equip/scss/add-detail.scss");

.add-equip-detail {
  .add-equip-content {
    .inspect-table-view {
      .px-form-item {
        margin-bottom: 0;
      }
    }

    .inspect-table-edit {
      .px-form-item {
        padding-top: 16px;
      }

      .px-form-item__content {
        padding-top: 16px;
      }

      :deep(.px-table__header) {
        .must::before {
          margin-right: 4px;
          color: var(--px-color-danger);
          content: "*";
        }
      }
      :deep(.px-table__cell) {
        padding: 0;
        height: 64px;
        line-height: 64px;
        .cell {
          height: 64px;
          line-height: 64px;
        }
      }
    }
  }
}
</style>
